package com.lxc.graduation.controller;

import com.lxc.graduation.entity.domain.Document;
import com.lxc.graduation.utils.DownLoadFileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ck
 * @Description:
 * @Date: Create in 20:50 2021/3/11
 */
@RestController
@RequestMapping("/api/pub/v1/document")
@Slf4j
public class DocumentController {
    @RequestMapping("exportWord")
    public void exportWord(HttpServletResponse response, @RequestBody Document document) throws Exception
    {

         log.info("文书生成开始");

        Map data = new HashMap<>();


        data.put("document", document);
        response.setHeader("content-Type", "application/msword");

        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;


        try {
            template = cfg.getTemplate("文书生成模板.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "文书生成模板");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         log.info("文书生成结束");
    }
}
